<script setup>
import { computed, ref, watch, onMounted } from 'vue';
import { EyeInvisibleOutlined, EyeTwoTone, VerticalRightOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn';
import { useRoute } from 'vue-router'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import rectangleBlue from "@/assets/rectangleBlue.png";
import { message } from 'ant-design-vue'
import PasswordTips from "@/components/PasswordTips.vue";
import {getStuInfo, stuRegister, updateStuInfo} from "@/api/stu.js";
import { sendEmailCode, updateEmail, userLogin } from '@/api/user.js'
import {userUserStore} from "@/stores/index.js";
import router from "@/router/router.js";

// 三张表单
const formRef1 = ref()
const formRef2 = ref()
const formRef3 = ref()
const route = useRoute()
const userStore = userUserStore()

//是否下一步

// 表单数据和验证
const phone = ref(route.query.phone)
const role = ref(route.query.role)
const formModel = ref({
  psd: '',
  repsd: '',
  username: '',
  email: '',
  code: '',
  realname: '',
  birth: ''
});

const currentStep = ref(0);
const isRegister = ref(false)
onMounted(() => {
  if(userStore.token){
    isRegister.value = true
    currentStep.value=1
  }
  //获取phone
  const getPhone = () => {
    if (!phone.value || role.value!=='student') {
      router.push('/register')
      message.error('出现异常');
    }
  };
  getPhone()

})

const updateUserInfo = async () => {
  const res = await getStuInfo()
  if (res.data.code === 200){
    userUserStore().setUserInfo(res.data.data)
  }else return message.error('更新信息失败')
}

// 日期的限制
const disabledDate = current => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)
  return current && current > today
}

// 计算当前年龄
const age = computed(() => {
  if (!formModel.value.birth) return null
  const today = new Date()
  const birthDate = new Date(formModel.value.birth)
  let age = today.getFullYear() - birthDate.getFullYear()
  const monthDiff = today.getMonth() - birthDate.getMonth()
  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
    age--
  }
  return age
})

// 步骤条
const nextStep = () => {
  if (currentStep.value < 2) {
    currentStep.value++;
  }
};
const prevStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--;
  }
};

// 密码验证
const validatepsd = async (_rules, value) => {
  if (value === '') {
    return Promise.reject('请输入密码');
  } else {
    if (value !== formModel.value.psd) {
      return Promise.reject('两次输入密码不一致');
    } else {
      return Promise.resolve();
    }
  }
};
const validaterepsd = async (_rules, value) => {
  if (value === '') {
    return Promise.reject('请再次输入密码');
  } else {
    if (value !== formModel.value.psd) {
      return Promise.reject('两次输入密码不一致');
    } else {
      return Promise.resolve();
    }
  }
};

// 下一步的验证，监听指定表单不符合规范就禁用下一步按钮
const nextSubmit = async () => {
  try {
    const res = await updateEmail({
      email: formModel.value.email,
      code: formModel.value.code
    })
    if (res.data.code === 200) {
     await updateUserInfo()
      nextStep()
      message.success('邮箱绑定成功')
    } else {
      message.error(res.data.message)
    }
  } catch (error) {
    message.error('请检查输入的信息')
  }
}

// 邮箱验证码
const isCounting = ref(false);
const isFalse = ref(true);
const count = ref(60);
const sendVerificationCode = async () => {
  await formRef2.value.validate(['email']).then(async => {
    if (isCounting.value) return;
    isFalse.value = false
    isCounting.value = true;
    count.value = 60;
    try {
      sendEmailCode({
        email: formModel.value.email
      })
    } catch {
      message.error('系统异常，请稍后重试')
    }
    const interval = setInterval(() => {
      count.value--;
      if (count.value <= 0) {
        clearInterval(interval);
        isCounting.value = false;
      }
    }, 1000);
  }).catch(() => {
    isCounting.value = true;
  })
};

//监听邮箱
watch(() => formModel.value.email, async () => {
  formRef2.value.validate(['email']).then(() => {
    isFalse.value = false
  }).catch(() => {
    isFalse.value = true
  })
})

// 前往上一步
const goToPreStep = () => {
  prevStep()
}

//跳过当前表单
const onSkip = () => {
  if (currentStep.value <= 1) {
    nextStep()
  } else {
    router.push('/jobinfo')
  }
}

//提交整个表单
const onRegister = async () => {
  await formRef1.value.validate().then(async () => {
    const res = await stuRegister({
      username: formModel.value.username,
      phoneNum: phone,
      password: formModel.value.psd,
      repassword: formModel.value.repsd,
    })
    if (res.data.code === 200) {
      localStorage.clear ()
      const res = await userLogin({
        role: role,
        phoneNum: phone,
        password: formModel.value.psd,
      })
      userStore.setToken(res.data.token)
      const resInfo = await getStuInfo()
      if(resInfo.data.code===200){
        userStore.setUserInfo(resInfo.data.data)
        message.success('注册成功,您已成功登录')
        nextStep()
      }else {
        throw new Error('获取用户信息失败')
      }
    } else {
      message.error(res.data.message)
    }
  }).catch((err) => {
    message.error(err||'请检查填写的信息')
  })
}

//同步到学生信息
const onSubmit = async () => {
  await formRef3.value.validate().then(async () => {
    const res = await updateStuInfo({
      username: formModel.value.username,
      email: formModel.value.email,
      realname: formModel.value.realname,
      birth: formModel.value.birth,
    })
    if (res.data.code === 200) {
      await updateUserInfo()
      router.push('/jobinfo')
      message.loading('前往主页中...', 1.5)
    } else {
      message.error('信息错误')
    }
  })
}

// 表单验证规则
const rules = {
  psd: [
    { required: true, validator: validatepsd, trigger: 'change' },
    {
      pattern: /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[!@#$%^&*(),.?":{}|<>_]).{8,20}$/,
      message: '密码必须满足下面的五个条件',
      trigger: 'change'
    }
  ],
  repsd: [{ required: true, validator: validaterepsd, trigger: 'change' }],
  username: [
    { required: true, message: '请输入用户名', trigger: 'change' },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'change' },
    { pattern: /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/, message: '请输入有效的邮箱地址', trigger: 'change' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'change' },
    {
      pattern: /^\d{6}$/,
      message: '请输入6位数字验证码',
      trigger: 'change'
    }
  ],
  realname: [{ required: true, message: '请输入真实姓名', trigger: 'change' }],
  birth: [{ required: true, message: '请选择出生日期', trigger: 'change' }]
};
dayjs.locale('zh-cn');
</script>


<template>
  <div class="main-container">
    <!-- Header -->
    <a-layout-header class="header">
      <h2 style="position: relative; top: -5px; left: 10px; color: #64d5c8;">实习招聘信息爬虫系统设计与实现</h2>
    </a-layout-header>

    <a-flex justify="center" align="center" gap="large" horizontal class="flex-container">
      <div class="card-container">
        <a-card class="form-wrapper">
          <div class="title-style">
            <a-image height="30px" width="10px" :src="rectangleBlue" :preview="false"></a-image>
            <span>完善账户信息</span>
          </div>
          <!-- 设置密码 -->
          <a-form ref="formRef1" v-if="currentStep === 0" :model="formModel" :rules="rules">
            <a-form-item label="" name="username">
              <a-input v-model:value="formModel.username" has-feedback placeholder="请输入用户名" style="height: 45px" />
            </a-form-item>
            <a-form-item label="" name="psd">
              <a-input-password v-model:value="formModel.psd" has-feedback placeholder="请输入密码" style="height: 45px" />
              <template #iconRender="v">
                <EyeTwoTone v-if="v"></EyeTwoTone>
                <EyeInvisibleOutlined v-else></EyeInvisibleOutlined>
              </template>
            </a-form-item>
            <a-form-item label="" name="repsd">
              <a-input-password v-model:value="formModel.repsd" has-feedback placeholder="请再次输入密码"
                                style="height: 45px" />
              <template #iconRender="v">
                <EyeTwoTone v-if="v"></EyeTwoTone>
                <EyeInvisibleOutlined v-else></EyeInvisibleOutlined>
              </template>
            </a-form-item>
            <a-form-item>
              <!--              :disabled="isNextSubmit" -->
              <a-button type="primary" @click="onRegister" block :disabled="isRegister">完成注册并登录</a-button>
            </a-form-item>
            <PasswordTips v-model:password="formModel.psd"></PasswordTips>
          </a-form>

          <!-- 设置用户名和邮箱 -->
          <a-form ref="formRef2" v-if="currentStep === 1" :model="formModel" :rules="rules">
            <div class="card-header">
              <div class="pre-step" @click="goToPreStep">
                <VerticalRightOutlined style="color: rgb(10, 124, 142)" />
                <span>上一步</span>
              </div>
              <div class="skip" @click="onSkip">
                <span>跳过</span>
              </div>
            </div>
            <a-form-item label="" name="email">
              <a-input v-model:value="formModel.email" has-feedback placeholder="请输入邮箱" style="height: 45px" />
            </a-form-item>
            <a-form-item label="" name="verificationCode">
              <a-input v-model:value="formModel.code" has-feedback placeholder="请输入验证码" style="height: 45px">
                <template #suffix>
                  <a-button type="link" @click="sendVerificationCode" :disabled="isCounting || isFalse">
                    {{ isCounting ? `${count}秒后重发` : '发送验证码' }}
                  </a-button>
                </template>
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" block @click="nextSubmit">下一步</a-button>
            </a-form-item>
          </a-form>

          <!-- 设置真实姓名和年龄 -->
          <a-form ref="formRef3" v-if="currentStep === 2" :model="formModel" :rules="rules">
            <div class="card-header">
              <div class="pre-step" @click="goToPreStep">
                <VerticalRightOutlined style="color: rgb(10, 124, 142)" />
                <span>上一步</span>
              </div>
              <div class="skip" @click="onSkip">
                <span>跳过</span>
              </div>
            </div>
            <a-form-item label="" name="realname">
              <a-input v-model:value="formModel.realname" has-feedback placeholder="请输入真实姓名" style="height: 45px" />
            </a-form-item>
            <a-form-item label="" name="birth">
              <a-input-group compact>
                <a-input disabled readonly class="data-picker-input" :placeholder="age">
                  <template #prefix>
                    <span>您的当前年龄</span>
                  </template>
                  <template #suffix>
                    <span>岁</span>
                  </template>
                </a-input>
                <a-date-picker :locale="locale" v-model:value="formModel.birth" placeholder="请选择出生日期"
                               :disabled-date="disabledDate" style="width: 40%" />
              </a-input-group>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" block @click="onSubmit">确认</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </div>
      <!-- 步骤条 -->
      <div class="step-container">
        <a-steps :current="currentStep" class="step" direction="vertical">
          <a-step disabled title="设置密码" />
          <a-step disabled title="设置用户名和邮箱" />
          <a-step disabled title="设置真实姓名和年龄" />
        </a-steps>
      </div>
    </a-flex>
  </div>
</template>

<style scoped>
a-input {
  height: 45px;
}

.form-wrapper {
  width: 400px;
  margin: 100px;
  height: 500px;
  box-shadow: 0 4px 8px rgba(10, 124, 142, 0.1),
  0 -4px 8px rgba(10, 124, 142, 0.1),
  -4px 0 8px rgba(10, 124, 142, 0.1),
  4px 0 8px rgba(10, 124, 142, 0.1);
  padding: 20px;
  border-radius: 8px;
}

.title-style {
  display: flex;
  margin-top: 70px;
  text-align: left;
  font-size: 22px;
  color: rgb(10, 124, 142);
  transform: translateY(-30px);
  align-items: center;

  >span {
    position: absolute;
    margin-left: 20px;
  }
}

.step {
  height: 500px;
  transform: translateY(100px);
}

.flex-container {
  max-height: calc(100vh - 150px);
  width: 100%;
  /*background: url("src/assets/detailContent.png") center / cover no-repeat;*/
}

.check-mark {
  color: green;
  margin-left: 5px;
}

.psd-request {
  margin-left: -20px;
  margin-top: 30px;
}

.psd-request li.valid {
  color: green;
}

.psd-request li {
  font-size: 10px;
  color: #999999;
  white-space: nowrap;
}

.card-header {
  display: flex;
  justify-content: space-between;
}

.pre-step {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  cursor: pointer;

  >span {
    color: rgb(10, 124, 142);
    font-size: 12px;
  }
}

.skip {
  cursor: pointer;
  display: flex;
  text-align: center;

  >span {
    color: rgb(10, 124, 142);
    font-size: 14px;
  }
}

.header {
  height: 50px;
  background: url("src/assets/headerBg.png") center / cover no-repeat;
  color: #fff;
  padding: 16px;
}

.main-container {
  height: 100vh;
  position: absolute;
  width: 100%;
}

.data-picker-input {
  width: 60%;
  color: rgb(10, 124, 142);
  text-align: center;
  border-right: none
}
</style>
